package com.active.hackson.app.web;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.active.hackson.app.beans.grid.RequestTableModel;
import com.active.hackson.app.beans.grid.ResponseTableModel;
import com.active.hackson.app.entities.AppUser;
import com.active.hackson.common.utils.JSONUtil;
import com.active.hackson.common.web.BaseController;




@Controller
public class GridDataController extends BaseController {

  @RequestMapping("dataOper")
  @ResponseBody
  public String dataOper( RequestTableModel reqModel, AppUser entity ) {
    String oper = reqModel.getOper();
    if ( reqModel.ADD.equals( oper ) || reqModel.EDIT.equals( oper ) ) {
      if ( entity.getId().equals( "_empty" ) ) {    // hack for jqgrid
        entity.setId( null );
      }
      commonService.saveOrUpdate( entity );
      return null;
    }
    else if ( reqModel.DEL.equals( oper ) ) {
      commonService.delete( entity );
      return null;
    } else if(reqModel.GET.equals( oper )) {
      DetachedCriteria criteria = DetachedCriteria.forClass(AppUser.class).add(Property.forName("id").isNotNull() );
      
      List users = commonService.findByExample( entity );
      

      return JSONUtil.toJSON( new ResponseTableModel( reqModel, users ) );
    }
    else {
      List<AppUser> users = commonService.loadAll( AppUser.class );
      return JSONUtil.toJSON( new ResponseTableModel( reqModel, users ) );
    }

  }

}
